#include "DirectXModel.h"

DXModel::DXModel (LPDIRECT3DDEVICE9 DrawDevice, LPCWSTR FileName)
{
	Device = DrawDevice;
	D3DXMatrixIdentity(&Transformation);
	if (FileName)
		LoadFromFile(FileName);
}

DXModel::~DXModel (void)
{
	if (Model)
		Model->Release();
	if (Textures)
		delete[] Textures;
	if (Materials)
		delete[] Materials;
	if (MaterialBuffer)
		MaterialBuffer->Release();
}

BOOL DXModel::LoadFromFile (LPCWSTR FileName)
{
	BOOL Success = TRUE;

	Success = D3DXLoadMeshFromX(FileName, D3DXMESH_MANAGED, Device, NULL,
								&MaterialBuffer, NULL, &NumMaterials, &Model);
	ExtractMaterialInfo();

	return Success;
}

void DXModel::Draw (void)
{
	for (DWORD i = 0; i < NumMaterials; i++)
	{
		Device->SetTransform(D3DTS_WORLD, &Transformation);
		Device->SetMaterial(&Materials[i]);
		if (Textures[i])
			Device->SetTexture(0, Textures[i]);
		Model->DrawSubset(i);
	}
}

void DXModel::Rotate (float Xdeg, float Ydeg, float Zdeg)
{
	D3DXMATRIX TempX, TempY, TempZ;
	D3DXMatrixRotationX (&TempX, Xdeg);
	D3DXMatrixRotationY (&TempY, Ydeg);
	D3DXMatrixRotationZ (&TempZ, Zdeg);
	Rotation = (TempX * TempY * TempZ);
	Transformation *= Rotation;
}

void DXModel::Translate (float X, float Y, float Z)
{
	D3DXMatrixIdentity(&Translation);
	D3DXMatrixTranslation(&Translation, X, Y, Z);
	Transformation *= Translation;
}

void DXModel::Scale (float XVal, float YVal, float ZVal)
{
	D3DXMatrixIdentity(&Scalar);
	D3DXMatrixScaling(&Scalar, XVal, YVal, ZVal);
	Transformation *= Scalar;
}

void DXModel::ExtractMaterialInfo (void)
{
	D3DXMATERIAL* TempMat = (D3DXMATERIAL*)MaterialBuffer->GetBufferPointer();

	Materials = new D3DMATERIAL9[NumMaterials];
	Textures = new LPDIRECT3DTEXTURE9[NumMaterials];

	for (DWORD i = 0; i < NumMaterials; i++)
	{
		Materials[i] = TempMat[i].MatD3D;
		Materials[i].Ambient = Materials[i].Diffuse;
		USES_CONVERSION;
		if (FAILED(D3DXCreateTextureFromFile(Device,
											 CA2W(TempMat[i].pTextureFilename), 
											 &Textures[i])))
			Textures[i] = NULL;
	}
}